package com.mxpio.erp.quality.controller;


import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.quality.entity.InspectionScheme;
import com.mxpio.erp.common.quality.entity.InspectionSchemeLine;
import com.mxpio.erp.common.quality.service.InspectionSchemeChainService;
import com.mxpio.erp.common.quality.service.InspectionSchemeLineService;
import com.mxpio.erp.common.quality.service.InspectionSchemeService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "InspectionSchemeController", description = "质检方案接口")
@RestController
@RequestMapping("/erp/quality/is/")
public class InspectionSchemeController {

    @Autowired
    private InspectionSchemeService service;

    @Autowired
    private InspectionSchemeLineService lineService;
    @Autowired
    private InspectionSchemeChainService inspectionSchemeChainService;
    @GetMapping("list")
    @Operation(summary = "质检方案列表", description = "获取质检方案列表（无分页）", method = "GET")
    public Result<List<InspectionScheme>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<InspectionScheme> schemeList = service.list(InspectionScheme.class, criteria);
        return Result.OK(schemeList);
    }

    @GetMapping("page")
    @Operation(summary = "质检方案列表", description = "获取质检方案列表（分页）", method = "GET")
    public Result<Page<InspectionScheme>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<InspectionScheme> schemeList = service.listPage(InspectionScheme.class, page, criteria);
        return Result.OK(schemeList);
    }

    @GetMapping("list/{code}")
    @Operation(summary = "根据schemeCode获取质检方案", description = "根据schemeCode获取质检方案", method = "GET")
    public Result<InspectionScheme> getById(@Parameter(description="通知单号") @PathVariable(name = "code", required = true) String code) {
        InspectionScheme schemeList = service.getById(InspectionScheme.class, code);
        return Result.OK(schemeList);
    }

    @PostMapping("add")
    @Operation(summary = "新增质检方案", description = "新增质检方案", method = "POST")
    public Result<InspectionScheme> add(@RequestBody InspectionScheme scheme) {
        service.save(scheme);
        return Result.OK(scheme);
    }

    @RequestMapping("save")
    @Operation(summary = "保存质检方案", description = "保存质检方案")
    public Result<InspectionScheme> save(@RequestBody InspectionScheme inspectionScheme) {
        service.save(inspectionScheme,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof InspectionSchemeLine){
                    InspectionScheme inspectionScheme = context.getParent();
                    ((InspectionSchemeLine) o).setSchemeCode(inspectionScheme.getCode());
                }
                return true;
            }
        });
        return Result.OK(inspectionScheme);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑质检方案", description = "编辑质检方案", method = "PUT")
    public Result<InspectionScheme> edit(@RequestBody InspectionScheme scheme) {
        service.update(scheme);
        return Result.OK(scheme);
    }

    @DeleteMapping("remove/{codes}")
    @Operation(summary = "根据codes删除质检方案", description = "删除质检方案", method = "DELETE")
    public Result<InspectionScheme> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "codes", required = true) String codes) {
        String[] code = codes.split(",");
        for(String key : code){
            Criteria c = Criteria.create().addCriterion("schemeCode", Operator.EQ, key);
            lineService.removeBatch(InspectionSchemeLine.class, c);
            //处理方案关联的物料或者物料组
            inspectionSchemeChainService.removeBySchemeCode(key);
            service.delete(InspectionScheme.class, key);
        }
        return Result.OK();
    }


    @PutMapping("submit/{code}")
    @Operation(summary = "提交质检方案", description = "提交质检方案", method = "PUT")
    public Result<InspectionScheme> submit(@Parameter(description="质检方案编码") @PathVariable(name = "code", required = true) String code) {
        InspectionScheme inspectionScheme = service.getById(InspectionScheme.class,code);
        if(inspectionScheme.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
            return service.updateBpmnStatus(inspectionScheme, OrderStatusEnums.BpmnStatus.AUDITING);
        }else {
            return Result.error("非开立状态不可提交");
        }
    }

    @PutMapping("audit/{code}")
    @Operation(summary = "审核质检方案", description = "审核质检方案", method = "PUT")
    public Result<InspectionScheme> audit(@Parameter(description = "质检方案编码") @PathVariable(name = "code", required = true) String code) {
        InspectionScheme inspectionScheme = service.getById(InspectionScheme.class,code);
        if (inspectionScheme.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
            return service.updateBpmnStatus(inspectionScheme, OrderStatusEnums.BpmnStatus.AUDITED);
        } else {
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("abandon/{code}")
    @Operation(summary = "弃审质检方案", description = "弃审质检方案", method = "PUT")
    public Result<InspectionScheme> abandon(@Parameter(description = "质检方案编码") @PathVariable(name = "code", required = true) String code) {
        InspectionScheme inspectionScheme = service.getById(InspectionScheme.class,code);
        if (inspectionScheme.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode()) || inspectionScheme.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            return service.updateBpmnStatus(inspectionScheme, OrderStatusEnums.BpmnStatus.CREATE);
        } else {
            return Result.error("非审核中、已审核状态不可审核");
        }
    }

}
